<?php
namespace app\admin\controller;

use app\admin\model\AuthRule as AuthRuleModel;
use think\Db;

class AuthRule extends Common
{
    public function lst()
    {
        $authRule = new AuthRuleModel();
        if(request()->isPost()){
            $sorts=input('post.');
            foreach ($sorts as $k=>$v){
                $authRule->update(['id'=>$k,'sort'=>$v]);
            }
            $this->success('更新排序成功',url('lst'));
            return;
        }
        $authRuleRes = $authRule->authRuleTree();
        $this->assign('authRuleRes',$authRuleRes);
        return view('list');
    }

    public function add()
    {
        if(request()->isPost()){
            $data = input('post.');
            $plevel = db('auth_rule')->field('level')->where('id',$data['pid'])->find();
            if($plevel){
                $data['level']= $plevel['level']+1;
            }else{
                $data['level']=0;
            }

            $add = db('auth_rule')->insert($data);
            if($add){
                $this->success('添加权限成功',url('lst'));
            }else{
                $this->error('添加权限失败');
            }
            return;
        }
        $authRule =  new AuthRuleModel();
        $authrule = $authRule->authRuleTree();
        $this->assign('authrule',$authrule);
        return view();
    }


    public function edit($id)
    {
        $authRule = new AuthRuleModel();
        if(request()->isPost()){
            $data = input('post.');
            $plevel=db('auth_rule')->field('level')->where('id',$data['pid'])->find();
            if($plevel){
                $data['level'] = $plevel['level']+1;
            }else{
                $data['level']=0;
            }
            $save = $authRule->update($data,['id'=>$id]);
            if($save!==false){
                $this->success('修改权限成功',url('lst'));
            }else{
                $this->error('修改权限失败');
            }
            return;
        }
        $authRules = $authRule->find($id);
        $authrule = $authRule->authRuleTree();
        $this->assign(array(
            'authRules'=>$authRules,
            'authrule'=>$authrule,
        ));
        return view();
    }

    public function del($id)
    {
        $authRule = new AuthRuleModel();
        $authRule->getparentid($id);

        $authRulesIds = $authRule->getchildrenid($id);
        $authRulesIds[] =$id;
        $del = $authRule::destroy($authRulesIds);
        if($del){
            $this->success('删除权限成功',url('lst'));
        }else{
            $this->error('删除权限失败');
        }
    }




}
